package net.yihang.miaosha.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

// 等价于spring的一段配置项信息，把某个bean交给容器控制反转
@Configuration
public class RedisConfig {

    @Autowired
    private RedisProperties properties;

    @Bean // 类似于 <bean ...> 作用把这个方法返回的对象交给spring容器管理
    @ConditionalOnProperty(prefix = "redis", name = "use-password", havingValue = "yes", matchIfMissing = false)
    // 只会调用一次，对象也是单例的
    public JedisPool jedisPool() {
        System.out.println("============using password...");
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(properties.getMaxTotal());
        config.setMinIdle(properties.getMinIdle());
        config.setMaxWaitMillis(properties.getMaxWait() * 1000);

        JedisPool pool = new JedisPool(config,
                properties.getHost(),
                properties.getPort(),
                properties.getTimeout() * 1000,
                properties.getPassword(), 0);
        return pool;
    }

    @Bean // 类似于 <bean ...> 作用把这个方法返回的对象交给spring容器管理
    @ConditionalOnProperty(prefix = "redis", name = "use-password", havingValue = "no", matchIfMissing = true)
    // 只会调用一次，对象也是单例的
    public JedisPool jedis() {
        System.out.println("============not using password...");
        JedisPool pool = new JedisPool(properties.getHost());
        return pool;
    }

    @Bean
    public JedisExecutor jedisExecutorContext(JedisPool pool) {
        return new JedisExecutor(pool);
    }

}
